package org.springframework.security.web.authentication.ui;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
import org.springframework.web.util.HtmlUtils;

/**
 * @author Dillon
 * @date 2024/6/28
 * @slogan 致敬大师 致敬未来的你
 * @desc spring过滤器链中的一个，位于过滤器链的第 17 位， 默认开启
 * 用于生成一个默认的登录页面，当进行表单登录时，如果没有提供自定义的登录页面，则会使用该类的登录页面
 */
public class DefaultLoginPageGeneratingFilter extends GenericFilterBean {

	/**
	 * 默认登录路径
	 */
	public static final String DEFAULT_LOGIN_PAGE_URL = "/login";

	/**
	 * 默认错误页面路径
	 */
	public static final String ERROR_PARAMETER_NAME = "error";

	/**
	 * 登录路径
	 */
	private String loginPageUrl;

	/**
	 * 登出成功路径
	 */
	private String logoutSuccessUrl;

	/**
	 * 错误页面URL路径 默认为 /login?error
	 */
	private String failureUrl;

	/**
	 * 是否允许表单登录
	 */
	private boolean formLoginEnabled;

	/**
	 * 是否允许 oauth2 登录
	 */
	private boolean oauth2LoginEnabled;

	/**
	 * 是否允许 saml2登录
	 */
	private boolean saml2LoginEnabled;

	/**
	 * 登录请求url
	 */
	private String authenticationUrl;

	/**
	 * 登录请求 userName key
	 */
	private String usernameParameter;

	/**
	 * 登录请求 password key
	 */
	private String passwordParameter;

	/**
	 * 记住我参数
	 */
	private String rememberMeParameter;

	private Map<String, String> oauth2AuthenticationUrlToClientName;

	private Map<String, String> saml2AuthenticationUrlToProviderName;

	private Function<HttpServletRequest, Map<String, String>> resolveHiddenInputs = (request) -> Collections.emptyMap();

	public DefaultLoginPageGeneratingFilter() {
	}

	public DefaultLoginPageGeneratingFilter(UsernamePasswordAuthenticationFilter authFilter) {
		this.loginPageUrl = DEFAULT_LOGIN_PAGE_URL;
		this.logoutSuccessUrl = DEFAULT_LOGIN_PAGE_URL + "?logout";
		this.failureUrl = DEFAULT_LOGIN_PAGE_URL + "?" + ERROR_PARAMETER_NAME;
		if (authFilter != null) {
			initAuthFilter(authFilter);
		}
	}

	private void initAuthFilter(UsernamePasswordAuthenticationFilter authFilter) {
		this.formLoginEnabled = true;
		this.usernameParameter = authFilter.getUsernameParameter();
		this.passwordParameter = authFilter.getPasswordParameter();
		if (authFilter.getRememberMeServices() instanceof AbstractRememberMeServices rememberMeServices) {
			this.rememberMeParameter = rememberMeServices.getParameter();
		}
	}

	/**
	 * Sets a Function used to resolve a Map of the hidden inputs where the key is the
	 * name of the input and the value is the value of the input. Typically this is used
	 * to resolve the CSRF token.
	 *
	 * @param resolveHiddenInputs the function to resolve the inputs
	 */
	public void setResolveHiddenInputs(Function<HttpServletRequest, Map<String, String>> resolveHiddenInputs) {
		Assert.notNull(resolveHiddenInputs, "resolveHiddenInputs cannot be null");
		this.resolveHiddenInputs = resolveHiddenInputs;
	}

	/**
	 * 是否允许表单或者 oauth2 或者 saml2登录
	 *
	 * @return 是否允许以上三种配置之一扽两个
	 */
	public boolean isEnabled() {
		return this.formLoginEnabled || this.oauth2LoginEnabled || this.saml2LoginEnabled;
	}

	/**
	 * 设置登出成功URL
	 *
	 * @param logoutSuccessUrl 登出成功URL
	 */
	public void setLogoutSuccessUrl(String logoutSuccessUrl) {
		this.logoutSuccessUrl = logoutSuccessUrl;
	}

	public String getLoginPageUrl() {
		return this.loginPageUrl;
	}

	/**
	 * 设置登录路径
	 *
	 * @param loginPageUrl 登录路径
	 */
	public void setLoginPageUrl(String loginPageUrl) {
		this.loginPageUrl = loginPageUrl;
	}

	/**
	 * 设置错误页面
	 *
	 * @param failureUrl 请求错误路径
	 */
	public void setFailureUrl(String failureUrl) {
		this.failureUrl = failureUrl;
	}

	/**
	 * 设置是否允许表单登录
	 *
	 * @param formLoginEnabled 是否允许表单登录标记
	 */
	public void setFormLoginEnabled(boolean formLoginEnabled) {
		this.formLoginEnabled = formLoginEnabled;
	}

	/**
	 * 设置是否允许oauth2 登录
	 *
	 * @param oauth2LoginEnabled oauth2 登录允许标记
	 */
	public void setOauth2LoginEnabled(boolean oauth2LoginEnabled) {
		this.oauth2LoginEnabled = oauth2LoginEnabled;
	}

	public void setSaml2LoginEnabled(boolean saml2LoginEnabled) {
		this.saml2LoginEnabled = saml2LoginEnabled;
	}

	public void setAuthenticationUrl(String authenticationUrl) {
		this.authenticationUrl = authenticationUrl;
	}

	public void setUsernameParameter(String usernameParameter) {
		this.usernameParameter = usernameParameter;
	}

	public void setPasswordParameter(String passwordParameter) {
		this.passwordParameter = passwordParameter;
	}

	public void setRememberMeParameter(String rememberMeParameter) {
		this.rememberMeParameter = rememberMeParameter;
	}

	public void setOauth2AuthenticationUrlToClientName(Map<String, String> oauth2AuthenticationUrlToClientName) {
		this.oauth2AuthenticationUrlToClientName = oauth2AuthenticationUrlToClientName;
	}

	public void setSaml2AuthenticationUrlToProviderName(Map<String, String> saml2AuthenticationUrlToProviderName) {
		this.saml2AuthenticationUrlToProviderName = saml2AuthenticationUrlToProviderName;
	}

	/**
	 * 执行过滤器
	 *
	 * @param request  请求对象
	 * @param response 响应对象
	 * @param chain    VirtualFilterChain 虚拟的过滤器链对象
	 * @throws IOException      执行异常
	 * @throws ServletException 执行异常
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain);
	}

	/**
	 * 执行过滤器实际逻辑
	 *
	 * @param request  请求对象
	 * @param response 响应对象
	 * @param chain    VirtualFilterChain 虚拟的过滤器链对象
	 * @throws IOException      执行异常
	 * @throws ServletException 执行异常
	 */
	private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
		// 获取当前请求路径是否为错误请求路径
		boolean loginError = isErrorPage(request);
		// 获取当前请求路径是否为登出路径
		boolean logoutSuccess = isLogoutSuccess(request);
		// 判断当前路径是否为登录路径
		boolean loginUrlRequest = isLoginUrlRequest(request);
		// 如果为登录 登出 错误请求，则认为需要跳转到登录页面，否则不做处理，执行下一个过滤器
		if (loginUrlRequest || loginError || logoutSuccess) {
			// 生成对应的HTML页面
			String loginPageHtml = generateLoginPageHtml(request, loginError, logoutSuccess);
			// 设置响应信息 并回写至客户端
			response.setContentType("text/html;charset=UTF-8");
			response.setContentLength(loginPageHtml.getBytes(StandardCharsets.UTF_8).length);
			response.getWriter().write(loginPageHtml);
			return;
		}
		// 执行下一个过滤器
		chain.doFilter(request, response);
	}

	/**
	 * 拼装默认的登录页面 html
	 *
	 * @param request       请求对象
	 * @param loginError    请求错误路径
	 * @param logoutSuccess 登出路径
	 * @return 拼装HTML页面
	 */
	private String generateLoginPageHtml(HttpServletRequest request, boolean loginError, boolean logoutSuccess) {
		String errorMsg = loginError ? getLoginErrorMessage(request) : "Invalid credentials";
		String contextPath = request.getContextPath();
		StringBuilder sb = new StringBuilder();
		sb.append("<!DOCTYPE html>\n");
		sb.append("<html lang=\"en\">\n");
		sb.append("  <head>\n");
		sb.append("    <meta charset=\"utf-8\">\n");
		sb.append("    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n");
		sb.append("    <meta name=\"description\" content=\"\">\n");
		sb.append("    <meta name=\"author\" content=\"\">\n");
		sb.append("    <title>Please sign in</title>\n");
		sb.append("    <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css\" "
				+ "rel=\"stylesheet\" integrity=\"sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M\" crossorigin=\"anonymous\">\n");
		sb.append("    <link href=\"https://getbootstrap.com/docs/4.0/examples/signin/signin.css\" "
				+ "rel=\"stylesheet\" integrity=\"sha384-oOE/3m0LUMPub4kaC09mrdEhIc+e3exm4xOGxAmuFXhBNF4hcg/6MiAXAf5p0P56\" crossorigin=\"anonymous\"/>\n");
		sb.append("  </head>\n");
		sb.append("  <body>\n");
		sb.append("     <div class=\"container\">\n");
		if (this.formLoginEnabled) {
			sb.append("      <form class=\"form-signin\" method=\"post\" action=\"").append(contextPath).append(this.authenticationUrl).append("\">\n");
			sb.append("        <h2 class=\"form-signin-heading\">Please sign in</h2>\n");
			sb.append(createError(loginError, errorMsg)).append(createLogoutSuccess(logoutSuccess)).append("        <p>\n");
			sb.append("          <label for=\"username\" class=\"sr-only\">Username</label>\n");
			sb.append("          <input type=\"text\" id=\"username\" name=\"").append(this.usernameParameter).append("\" class=\"form-control\" placeholder=\"Username\" required autofocus>\n");
			sb.append("        </p>\n");
			sb.append("        <p>\n");
			sb.append("          <label for=\"password\" class=\"sr-only\">Password</label>\n");
			sb.append("          <input type=\"password\" id=\"password\" name=\"").append(this.passwordParameter).append("\" class=\"form-control\" placeholder=\"Password\" required>\n");
			sb.append("        </p>\n");
			sb.append(createRememberMe(this.rememberMeParameter)).append(renderHiddenInputs(request));
			sb.append("        <button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\">Sign in</button>\n");
			sb.append("      </form>\n");
		}
		if (this.oauth2LoginEnabled) {
			sb.append("<h2 class=\"form-signin-heading\">Login with OAuth 2.0</h2>");
			sb.append(createError(loginError, errorMsg));
			sb.append(createLogoutSuccess(logoutSuccess));
			sb.append("<table class=\"table table-striped\">\n");
			for (Map.Entry<String, String> clientAuthenticationUrlToClientName : this.oauth2AuthenticationUrlToClientName
					.entrySet()) {
				sb.append(" <tr><td>");
				String url = clientAuthenticationUrlToClientName.getKey();
				sb.append("<a href=\"").append(contextPath).append(url).append("\">");
				String clientName = HtmlUtils.htmlEscape(clientAuthenticationUrlToClientName.getValue());
				sb.append(clientName);
				sb.append("</a>");
				sb.append("</td></tr>\n");
			}
			sb.append("</table>\n");
		}
		if (this.saml2LoginEnabled) {
			sb.append("<h2 class=\"form-signin-heading\">Login with SAML 2.0</h2>");
			sb.append(createError(loginError, errorMsg));
			sb.append(createLogoutSuccess(logoutSuccess));
			sb.append("<table class=\"table table-striped\">\n");
			for (Map.Entry<String, String> relyingPartyUrlToName : this.saml2AuthenticationUrlToProviderName
					.entrySet()) {
				sb.append(" <tr><td>");
				String url = relyingPartyUrlToName.getKey();
				sb.append("<a href=\"").append(contextPath).append(url).append("\">");
				String partyName = HtmlUtils.htmlEscape(relyingPartyUrlToName.getValue());
				sb.append(partyName);
				sb.append("</a>");
				sb.append("</td></tr>\n");
			}
			sb.append("</table>\n");
		}
		sb.append("</div>\n");
		sb.append("</body></html>");
		return sb.toString();
	}

	/**
	 * 获取错误页面提示消息
	 *
	 * @param request 请求对象
	 * @return 错误页面提示消息
	 */
	private String getLoginErrorMessage(HttpServletRequest request) {
		HttpSession session = request.getSession(false);
		if (session == null) {
			return "Invalid credentials";
		}
		if (!(session.getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION) instanceof AuthenticationException exception)) {
			return "Invalid credentials";
		}
		if (!StringUtils.hasText(exception.getMessage())) {
			return "Invalid credentials";
		}
		return exception.getMessage();
	}

	/**
	 * 拼装表单隐藏输入 dev标签
	 *
	 * @param request 请求对象
	 * @return 标签字符串
	 */
	private String renderHiddenInputs(HttpServletRequest request) {
		StringBuilder sb = new StringBuilder();
		for (Map.Entry<String, String> input : this.resolveHiddenInputs.apply(request).entrySet()) {
			sb.append("<input name=\"");
			sb.append(input.getKey());
			sb.append("\" type=\"hidden\" value=\"");
			sb.append(input.getValue());
			sb.append("\" />\n");
		}
		return sb.toString();
	}

	/**
	 * 渲染记住我标签
	 *
	 * @param paramName 参数名称
	 * @return 标签字符串
	 */
	private String createRememberMe(String paramName) {
		if (paramName == null) {
			return "";
		}
		return "<p><input type='checkbox' name='" + paramName + "'/> Remember me on this computer.</p>\n";
	}

	/**
	 * 判断当前路径是否为登出路径
	 *
	 * @param request 请求对象
	 * @return 是否登出请求路径
	 */
	private boolean isLogoutSuccess(HttpServletRequest request) {
		return this.logoutSuccessUrl != null && matches(request, this.logoutSuccessUrl);
	}

	/**
	 * 判断当前路径是否为登录路径
	 *
	 * @param request 请求对象
	 * @return 是否为登录请求路径
	 */
	private boolean isLoginUrlRequest(HttpServletRequest request) {
		return matches(request, this.loginPageUrl);
	}

	/**
	 * 判断请求路径是否为请求失败URL
	 *
	 * @param request 请求对象
	 * @return 请求URL是否为失败URL
	 */
	private boolean isErrorPage(HttpServletRequest request) {
		return matches(request, this.failureUrl);
	}

	/**
	 * 创建错误html 页面
	 *
	 * @param isError 是否为错误页面
	 * @param message 错误消息
	 * @return html 拼接字符串
	 */
	private String createError(boolean isError, String message) {
		if (!isError) {
			return "";
		}
		return "<div class=\"alert alert-danger\" role=\"alert\">" + HtmlUtils.htmlEscape(message) + "</div>";
	}

	/**
	 * 创建登录成功拼接div
	 *
	 * @param isLogoutSuccess 是否登录成功
	 * @return 登录成功提示字符串
	 */
	private String createLogoutSuccess(boolean isLogoutSuccess) {
		if (!isLogoutSuccess) {
			return "";
		}
		return "<div class=\"alert alert-success\" role=\"alert\">You have been signed out</div>";
	}

	/**
	 * 请求对象路径 是否匹配待匹配路径
	 *
	 * @param request 请求对象
	 * @param url     待匹配路径
	 * @return 是否匹配到路径
	 */
	private boolean matches(HttpServletRequest request, String url) {
		// 如果不是Get 或者 待匹配路径为null 则默认匹配失败
		if (!"GET".equals(request.getMethod()) || url == null) {
			return false;
		}
		// 获取请求路径 如果路径是 存在 ; 则获取 ; 前面的路径 真实路径
		String uri = request.getRequestURI();
		int pathParamIndex = uri.indexOf(';');
		if (pathParamIndex > 0) {
			uri = uri.substring(0, pathParamIndex);
		}
		// 获取并拼装Get请求参数
		if (request.getQueryString() != null) {
			uri += "?" + request.getQueryString();
		}
		// 如果未配置上下文，则直接将请求对象url 与 url匹配
		if ("".equals(request.getContextPath())) {
			return uri.equals(url);
		}
		// 如果配置上下文 ，则拼接上下文进行比较
		return uri.equals(request.getContextPath() + url);
	}

}
